package com.example.dao;

import com.example.annotation.Autowired;
import com.example.annotation.Repository;
import com.example.pojo.Account;
import com.example.utils.ConnectionUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 标记@Repository("testAccount")
 * 使用 "testAccount"，向集合中注册当前类；
 * 创建私有属性：connectionUtils
 * 对私有属性标记： @Autowired，从集合中属性类型首字母小写获取对象赋值
 * 提取公共个获取预编译sql PreparedStatement方法，
 *
 * @author kangshuai
 */
@Repository("testAccount")
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private ConnectionUtils connectionUtils;

    @Override
    public Account queryAccountByCardNo(String cardNo) throws Exception {
        PreparedStatement preparedStatement = preparedStatementHandle("select * from account where cardNo=?");
        preparedStatement.setString(1, cardNo);
        ResultSet resultSet = preparedStatement.executeQuery();

        Account account = new Account();
        while (resultSet.next()) {
            account.setCardNo(resultSet.getString("cardNo"));
            account.setName(resultSet.getString("name"));
            account.setMoney(resultSet.getInt("money"));
        }
        resultSet.close();
        preparedStatement.close();
        return account;
    }

    @Override
    public int updateAccountByCardNo(Account account) throws Exception {
        PreparedStatement preparedStatement = preparedStatementHandle("update account set money=? where cardNo=?");
        preparedStatement.setInt(1, account.getMoney());
        preparedStatement.setString(2, account.getCardNo());
        int i = preparedStatement.executeUpdate();
        preparedStatement.close();
        return i;
    }

    /**
     * 获取数据库链接
     * 提取公共个获取预编译sql PreparedStatement方法，
     *
     * @param sql
     * @return
     * @throws Exception
     */
    private PreparedStatement preparedStatementHandle(String sql) throws Exception {
        Connection con = connectionUtils.getCurrentThreadConn();
        return con.prepareStatement(sql);
    }
}
